var userManager = function() {
	var baseUrl = contextPath + '/auth/user/';
	var dialog = null;
	//对话框
	var userName = null;
	//用户名
	var userAccount = null;
	//用户账号
	var description = null;
	//描述
	var isEnable = null;
	//是否启用
	var dataGrid = null;
	
	var validityDate=null;
	//Grid对象
	
	/*
	 *新增
	 */
	var add = function(grid) {
		dataGrid = grid;
		$.get(contextPath + '/pages/auth/user-template.jsp').done(function(data) {
			addInit(data);
		});
	};
	function addInit(data){
		dialog = $(data);
		userName = dialog.find('#userName');
		
		userAccount = dialog.find('#userAccount');
		description = dialog.find('#description');
		validityDate=dialog.find('#validityDate');
        validityDate.datetimepicker({
			   format: "yyyy-mm-dd",
		       autoclose: true,
		       todayBtn: true,
		       minView: 2,
		       startView:2,
		       language: 'zh-CN'
		   }); 
		dialog.find('#save').on('click', function(){
			save();
		}).end().modal({
			keyboard : false
		}).on({
			'hidden.bs.modal' : function() {
				$(this).remove();
			},
			'complete' : function() {
				drgUI.success('保存成功');
				$(this).modal('hide');
                dataGrid.grid('refresh');
            }
		});
	}
	/*
	 * 修改
	 */
	var modify = function(item, grid) {
		dataGrid = grid;
		$.get(contextPath + '/pages/auth/user-template.jsp').done(function(data) {
			init(data, item);
			setData(item);
		});
	};
	/*
	 * 重置密码
	 */
	var resetPassword = function(data, grid) {
		var userIds=data.join(',');
		var dataGrid = grid;
		$.post(baseUrl + 'resetPassword.dhc',{'userIds':userIds}).done(function(data) {
			if (data.success) {				
				drgUI.success('重置密码成功，初始密码为:888888');
			} else {
				drgUI.error(data.errorMessage);
			}
		}).fail(function(data) {
			drgUI.error('重置密码失败');
		});
	};
	/*
	 * 可用
	 */
	var available = function(item, grid) {
		var dataGrid = grid;
		$.post(baseUrl + 'activate.dhc?userId=' + item.id).done(function(data) {		    
			if (data.success == true) {				
				drgUI.success('用户现在可用！');
				grid.grid('refresh');
			} else {
				drgUI.error(data.errorMessage);
			}
		}).fail(function(data) {
			drgUI.error('可用失败');
		});
	};
	/*
	 禁用
	 */
	var forbidden = function(item, grid) {
		var dataGrid = grid;
		$.post(baseUrl + 'suspend.dhc?userId=' + item.id).done(function(data) {		    
			if (data.success == true) {				
				drgUI.success('用户禁用成功！');
				grid.grid('refresh');
			} else {
				drgUI.error(data.errorMessage);
			}
		}).fail(function(data) {
			drgUI.error('禁用失败');
		});
	};

    /**
     * 删除多个用户
     * @param users 多个用户
     * @param grid
     */
	var deleteUser = function(users, grid) {

        var data = "";
        $.each(users, function(i, user){
            data += ("userIds=" + user.id + "&");
        });
        data = data.substring(0, data.length-1);

        dataGrid = grid;
		$.post(baseUrl + 'terminate.dhc', data).done(function(data){
			if(data.success){
				drgUI.success('撤销成功');
				dataGrid.grid('refresh');
			}else{
				drgUI.error(data.errorMessage);
			}
		}).fail(function(data){
			drgUI.error('撤销失败');
		});
	};

	/**
	 * 初始化
	 */
	var init = function(data, item) {
		dialog = $(data);
		dialog.find('.modal-header').find('.modal-title').html( item ? '修改用户信息' : '添加用户');
		userName = dialog.find('#userName');
		userAccount = dialog.find('#userAccount');
		description = dialog.find('#description');		
		validityDate = dialog.find('#validityDate');
		isEnable = dialog.find('[name="isEnable"]');
		isEnable.on('click', function() {
			isEnable.each(function() {
				$(this).parent().removeClass('checked');
			});
			$(this).parent().addClass('checked');
		});
		dialog.find('#save').on('click', function() {
			save(item);
		}).end().modal({
			keyboard : false
		}).on({
			'hidden.bs.modal' : function() {
				$(this).remove();
			},
			'complete' : function() {
				drgUI.success('保存成功');
				$(this).modal('hide');
				dataGrid.grid('refresh');
			}
		});
	};

	/*
	 *设置值
	 */
	var setData = function(item) {
		validityDate.datetimepicker({
			   format: "yyyy-mm-dd",
		       autoclose: true,
		       todayBtn: true,
		       minView: 2,
		       startView:2,
		       language: 'zh-CN'
		   });
		userName.val(item.name);
		userAccount.val(item.userAccount).attr('disabled', 'disabled');
		description.val(item.description);
		validityDate.val(new Date(item.validityDate).Format("yyyy-MM-dd"));
		if (!item.valid) {
			dialog.find('[name="isEnable"][value="true"]').removeAttr('checked', 'checked').parent().removeClass('checked');
			dialog.find('[name="isEnable"][value="false"]').attr('checked', 'checked').parent().addClass('checked'); 
		}
	};
	/*
	 *   保存数据 id存在则为修改 否则为新增
	 */
	var save = function(item) {
		if (!validate(item)) {
			dialog.find('#save').removeAttr('disabled');
			return false;
		}
		var url = baseUrl + 'add.dhc';
		if (item) {
			url = baseUrl + 'update.dhc';
		}
		
		$.post(url, getAllData(item)).done(function(data) {
			if (data.success) {
				dialog.trigger('complete');
			} else {
				drgUI.error(data.errorMessage);
			}
			dialog.find('#save').removeAttr('disabled');
		});
	};

	/**
	 * 数据验证
	 */
	var validate = function(item) {
		if (!Validation.notNull(dialog, userName, userName.val(), '请输入用户名称')) {
			return false;
		}
		if (!Validation.notNull(dialog, userAccount, userAccount.val(), '请输入用户账号')) {
			return false;
		}
		
		if (!Validation.checkByRegExp(dialog, userAccount, '^[0-9a-zA-Z]*$', userAccount.val(), '用户帐号只能输入字母及数字')) {
			return false;
		}
		return true;
	};
	/*
	 *获取表单数据
	 */
	var getAllData = function(item) {
		var data = {};
		data['name'] = userName.val();
		data['userAccount'] = userAccount.val();
		data['description'] = description.val();
		data['validityDate'] = validityDate.val();
		
		if (item) {
			data['id'] = item.id;
		}
		console.log(data)
		return data;
	};
	/**
	 * 指标配置
	 */
	var attrQuotas = function(item, grid, from){
		if (item.length == 1) {
			var role = "";
			var userCode = "";
			role = item[0].name;
			userCode = item[0].id;
			getQuotasByRole(userCode, role, function(data_1) {
				var data = data_1.data;
				for ( var o in data) {
					data[o].childOuter=false;//不能移除父节点
					//data[o].dropInner = false;
					data[o].dropRoot = false;
					data[o].drag=true;
				}
				var zTrees = arrayToTree(data, "id", "pid");
				getQuotaDialog(zTrees, userCode, role);
			});
		}else{
            drgUI.warning('请选择一条记录进行分配');
            return;
          }
		
		/**
		 * 根据角色code和名称获取指标
		 */
		function getQuotasByRole(userCode, roleCode, callback){
			$.post(contextPath + "/quota/getQuotasByRole.dhc", {userCode:userCode, roleCode:roleCode}).done(function(data){
				callback(data);
			});
		}		
		function getQuotaDialog(zTrees, userCode, roleCode){
			$.post(contextPath+"/pages/common/quota-tree.jsp").done(function(data){
				var dialog  = $(data);
				if($("#roles").html() == "超级管理员" || $("#roles").html() == "管理员") {
					dialog.find("#clear").css("display","none") ;
					dialog.find("#copyYiZheng_id").css("display","block") ;
				}
				dialog.find(".modal-title").html("指标配置选项");
				var str = '';
				str += '<div class="zTreeDemoBackground">';
				str += '<ul id="treeDemo" class="ztree" role="'+roleCode+'"></ul>';
				str += '</div>';
				dialog.find(".echartscq").html(str);
				if(roleCode==""){
					dialog.find("#clear").hide();
				}
				dialog.find("#mark").html('<label style="color: red;">备注:<br>1.若编辑指标(增、删)，请在节点上右键选择相应的操作.<br>2.可通过拖拽的方式调整指标顺序.</label>');				
				var setting = {
						view: {
							selectedMulti: false
						},
						check: {
							enable: true,
							chkStyle: "checkbox" ,
							chkboxType: { "Y": "ps", "N": "ps" }
						},
						edit: {
							drag: {
								autoExpandTrigger: true,
								prev: dropPrev,
								inner: dropInner,
								next: dropNext
							},
							enable: true,
							showRemoveBtn: false,
							showRenameBtn: false
						},
						callback: {
							beforeDrag: beforeDrag,
							onRightClick: OnRightClick
							
						}
					};				

				//复制医政快速生成指标树
                dialog.find('#copyYiZheng_id').on('click', function(){
                    drgUI.confirm({
                        content : '将快速生成医政角色指标方案',
                        callSure : function() {
                            getQuotasByRole('', '医政', function(data_1) {
                				var data = data_1.data;
                				for ( var o in data) {
                					data[o].childOuter=false;//不能移除父节点
                					//data[o].dropInner = false;
                					data[o].dropRoot = false;
                					data[o].drag=true;
                				}
                				var zTrees = arrayToTree(data, "id", "pid");
                				 $.fn.zTree.init(dialog.find("#treeDemo"), setting, zTrees);
                			}); 
                        }
                    });                  
                });
                $.fn.zTree.init(dialog.find("#treeDemo"), setting, zTrees);
				dialog.find('#save').on('click', function(){
					dialog.find('#save').attr("disabled", "");
					//清空之前的配置
					$.post(contextPath + "/quota/emptyQuotaSetting.dhc", {userCode: userCode, roleCode: roleCode}).done(function(data){
						if(!data.success){
							var errorLog = "保存失败,日志："+data.errorMessage;
							drgUI.error(errorLog);
						}else {
							var zTree = $.fn.zTree.getZTreeObj("treeDemo");
							zTrees = $.extend(true, [], zTree.getNodes());
							var nodes = zTree.getNodes();
							var cNodes = [];
							updateTrees(zTrees, "0", cNodes);
							var zTreeSimp = zTree.transformToArray(cNodes);
							var ajaxCount = zTreeSimp.length;
							var ajaxS = 0;
							var errorLog;
							var orderId=1;
							for(var o in zTreeSimp){
								var node = zTreeSimp[o];
								$.post(contextPath + "/quota/adminSaveQuotas.dhc", {param: JSON.stringify(node), userCode: userCode, roleCode: roleCode,orderId:orderId}).done(function(data){
									ajaxS ++;
									if(!data.success){
										errorLog += "指标("+node.code+")报错\n"+data.errorMessage;
										errorLog += "\n";
									}
								});
								orderId++;
							};
							var timer = setInterval(function(){
								if(ajaxS == ajaxCount){
									clearInterval(timer);
									if(errorLog){
										dialog.modal('hide');
										drgUI.error(errorLog);
									}else{
										dialog.trigger('complete');
									}
								}
							}, 500);
						}
					})
				}).end().modal({
					keyboard : false
				}).on({
					'hidden.bs.modal' : function() {
						dialog.remove();
					},
					'complete' : function() {
						dialog.modal('hide');
		            }
				});
				
				dialog.find('#clear').on('click', function(){
					  drgUI.confirm({
                        content : "即将清空该页面指标配置,请谨慎操作！",
                        callSure : function() {
						$.post(contextPath + "/quota/clearQuotaSettings.dhc", {userCode: userCode, roleCode: roleCode}).done(function(data){
	    					$.post(contextPath + "/quota/getQuotasByRole.dhc", {userCode: userCode, roleCode: roleCode}).done(function(data_1){
	    						if(data_1.data.length==0){
	    							drgUI.error('没有配置指标');
	    							return;
	    						}
	    						totalQuota = arrayToTree(data_1.data, "id", "pid");
	    						var zTrees = $.extend(true, [], totalQuota);
	    						$.fn.zTree.init(dialog.find("#treeDemo"), setting, zTrees);
	    					});
	    				});
					 }
                    }); 
				});
			})
		}
	};
	
	var homePageSetting = function(item, grid, from){
		if(item.length>0){
			if(item.length>1){
                drgUI.warning('请选择一条记录进行分配');
                return;
			}
			var role = item[0].name;
			$.post(contextPath+"/pages/common/top-dialog-buttons.jsp").done(function(data){
				var dialog  = $(data);
				dialog.find(".modal-title").html("设置首页");
				var str = '';
				str+="首页路径(相对)：<input size=100/>";
				str+="<br>";
				str+="示例:/pages/welcome.jsp"
				dialog.find(".echartscq").html(str);
				dialog.find(".echartscq").css("height", "50px");
				$.post(contextPath + "/auth/currentUser/getHomePageByRole.dhc", {role: role}).done(function(data){
            		if(data.success && data.data){
            			dialog.find(".echartscq>input").val(data.data)
            		}
            	});
				dialog.find('#save').on('click', function(){
					$.post(contextPath + "/auth/currentUser/saveHomePageSetting.dhc", {role: role, page: dialog.find(".echartscq>input").val()}).done(function(data){
						if(data.success){
			                drgUI.success('设置成功');
						}else{
			                drgUI.error(data.errorMessage);
						}
						dialog.trigger('complete');
					})
				}).end().modal({
					keyboard : false
				}).on({
					'hidden.bs.modal' : function() {
						dialog.remove();
					},
					'complete' : function() {
						dialog.modal('hide');
		            }
				});
			});
		}else{
            drgUI.warning('请选择一条记录进行分配');
		}
	}
	
	return {
		add : add,
		modify : modify,
		deleteUser : deleteUser,
		resetPassword : resetPassword,
		available : available,
		forbidden : forbidden,
		attrQuotas : attrQuotas,
		homePageSetting: homePageSetting
	};
}; 